<?php

/**
 * Description of Model
 *
 * @author superx
 * @package Core
 */
abstract class Core_Model extends Core_ArrayObject {

    protected $_dynamicProp = array();

    public function rules() {
        return array();
    }

    /**
     * @return Core_Db_Table|MongoCollection
     */
    public function getTable() {
        return $this->getDao()->getTable();
    }

    /**
     * @return Core_Dao
     */
    public function getDao() {
        $class = get_called_class();
        $table = str_replace('Model_', 'Dao_', $class);
        return $table::getInstance();
    }

    /**
     * @return int the last inserted id|int affected rows on update
     */
    public function save() {
        $pk = $this->getTable()->getPK();
        $data = $this->toArray();
        $data = array_filter($data, function ($var) {
            return $var !== NULL;
        });
        if ($this->$pk) {
            unset($data[$pk]);
            return $this->getDao()->update($data, $this->$pk);
        } else {
            $last_id = $this->getDao()->insert($data);
            if ($last_id) {
                $this->$pk = $last_id;
            }
            return $last_id;
        }
    }

    public function delete() {
        $pk = $this->getTable()->getPK();
        if ($this->$pk) {
            return $this->getDao()->delete($this->$pk);
        }
        return false;
    }

    public function propMap($key) {
        return null;
    }

    final public function __set($key, $value) {
        $this->_dynamicProp[$key] = $value;
    }

    final public function &__get($key) {
        if (!isset($this->_dynamicProp[$key])) {
            $this->_dynamicProp[$key] = $this->propMap($key);
        }
        return $this->_dynamicProp[$key];
    }

}
